package j5039.whcm.third.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.aliyun.oss.model.PutObjectRequest;
import j5039.whcm.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author lhc
 */
@RestController
@RequestMapping("third/oss")
public class UploadController {

        @Autowired
        OSS ossClient;

        @Value("${spring.cloud.alicloud.oss.endpoint}")
        String endpoint;
        @Value("${spring.cloud.alicloud.bucket}")
        String bucket;
        @Value("${spring.cloud.alicloud.access-key}")
        String accessId;

        @GetMapping("/policy")
        public R policy(){

//            String accessId = "<yourAccessKeyId>"; // 请填写您的AccessKeyId。
//            String accessKey = "<yourAccessKeySecret>"; // 请填写您的AccessKeySecret。
//            String endpoint = "oss-cn-hangzhou.aliyuncs.com"; // 请填写您的 endpoint。
//            String bucket = "bucket-name"; // 请填写您的 bucketname 。
            String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

            String dir = format.format(new Date())+"/"; // 用户上传文件时指定的前缀。

//            // 创建OSSClient实例。
//            OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
            try {
                long expireTime = 30;
                long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
                Date expiration = new Date(expireEndTime);
                // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
                PolicyConditions policyConds = new PolicyConditions();
                policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
                policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

                String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
                byte[] binaryData = postPolicy.getBytes("utf-8");
                String encodedPolicy = BinaryUtil.toBase64String(binaryData);
                String postSignature = ossClient.calculatePostSignature(postPolicy);

                Map<String, String> respMap = new LinkedHashMap<String, String>();
                respMap.put("accessid", accessId);
                respMap.put("policy", encodedPolicy);
                respMap.put("signature", postSignature);
                respMap.put("dir", dir);
                respMap.put("host", host);
                respMap.put("expire", String.valueOf(expireEndTime / 1000));
                // respMap.put("expire", formatISO8601Date(expiration));
                return R.ok().put("data",respMap);
            } catch (Exception e) {
                // Assert.fail(e.getMessage());
                System.out.println(e.getMessage());
                return R.error();
            } finally {
                ossClient.shutdown();
            }

        }


//    @PostMapping("/upload")
//    public void upload(MultipartFile file) throws IOException {
//        String endpoint = "http://oss-cn-beijing.aliyuncs.com";
//        String accessKeyId ="LTAI4GGxfugdwiKEGFJZENwj";
//        String accessKeySecret ="YASSIG2INReurR72V5j5dA2sN1RuCi";
//        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//        PutObjectRequest putObjectRequest = new PutObjectRequest("j5039-whcm","zz.jpg",file.getInputStream());
//        ossClient.putObject(putObjectRequest);
//        ossClient.shutdown();
//    }
}
